package com.ecarx.camera.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.ecarx.camera.utils.LogUtils;
import com.ecarx.camera.utils.Utils;
import com.ecarx.camera.worker.camera.dvr.DvrMonitor;

/**
 * Dvr状态监测Service
 */
public class DvrStateService extends Service {

    private static final String TAG = "DvrStateService";
    private static final String DVR_STATE_SERVICE_NAME = "com.ecarx.camera.service.DvrStateService";

    private DvrMonitor mDvrMonitor;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.d(TAG, "onCreate");
        mDvrMonitor = new DvrMonitor();
        mDvrMonitor.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "onDestroy");
        if (mDvrMonitor != null) {
            mDvrMonitor.stop();
        }
    }

    /**
     * 启动Dvr状态监测服务
     * @param context
     */
    public static void startIfNotRunning(Context context) {
        if (context == null) {
            return;
        }
        boolean isRunning = Utils.isServiceRunning(context, DVR_STATE_SERVICE_NAME);
        LogUtils.d(TAG, "start, isRunning:" + isRunning);
        if (!isRunning) {
            try {
                Intent serviceIntent = new Intent(context, DvrStateService.class);
                context.startService(serviceIntent);
            } catch (Throwable e) {
                LogUtils.e(TAG, "startService e:" + e);
            }
        }
    }

}
